import { defineStore } from "pinia";
import { ref, computed, watch } from "vue";
import { systemApi } from "@/api/services";
import type { RouteLocationNormalized } from "vue-router";
import type {
  AppInfo,
  SystemStatus,
  Notification,
  BreadcrumbItem,
} from "@/types/app";

// 访问记录类型
interface VisitedView {
  name: string;
  path: string;
  title: string;
  meta?: any;
}

// 窗口大小类型
interface WindowSize {
  width: number;
  height: number;
}

// 设备类型
type DeviceType = "desktop" | "tablet" | "mobile";

export const useAppStore = defineStore("app", () => {
  // 状态
  const loading = ref(false);
  const loadingText = ref("");
  const sidebarCollapsed = ref(false);
  const windowSize = ref<WindowSize>({ width: 1920, height: 1080 });
  const isOnline = ref(navigator.onLine);
  const isPageVisible = ref(!document.hidden);
  const visitedViews = ref<VisitedView[]>([]);
  const cachedViews = ref<string[]>([]);
  const appInfo = ref<AppInfo>({
    name: "CardCaptorSakura",
    version: "1.0.0",
    description: "多人格AI助手系统",
    author: "CardCaptorSakura Team",
    homepage: "https://cardcaptorsakura.com",
    repository: "https://github.com/cardcaptorsakura/cardcaptorsakura",
    license: "MIT",
    buildTime: "",
    commitHash: "",
    environment: "development",
  });

  const systemStatus = ref<SystemStatus>({
    online: true,
    serverTime: new Date().toISOString(),
    uptime: 0,
    version: "1.0.0",
    maintenance: false,
    maintenanceMessage: "",
    features: {
      chat: true,
      persona: true,
      multimodal: true,
      voice: false,
      image: true,
      file: true,
      export: true,
      backup: true,
    },
    limits: {
      maxSessions: 100,
      maxMessages: 10000,
      maxFileSize: 10 * 1024 * 1024, // 10MB
      maxPersonas: 50,
      dailyRequests: 1000,
    },
    stats: {
      totalUsers: 0,
      activeUsers: 0,
      totalSessions: 0,
      totalMessages: 0,
      totalPersonas: 0,
    },
  });

  const notifications = ref<Notification[]>([]);
  const error = ref<string | null>(null);
  const breadcrumbs = ref<BreadcrumbItem[]>([]);
  const pageTitle = ref("CardCaptorSakura");
  const isFullscreen = ref(false);
  const connectionStatus = ref<"connected" | "connecting" | "disconnected">(
    "connected",
  );
  const lastActivity = ref<Date>(new Date());
  const isIdle = ref(false);
  const idleTimeout = ref(30 * 60 * 1000); // 30分钟
  const shortcuts = ref<Record<string, string>>({
    "ctrl+k": "search",
    "ctrl+n": "new-chat",
    "ctrl+shift+p": "command-palette",
    "ctrl+/": "help",
    esc: "close-modal",
  });

  // 计算属性
  const deviceType = computed<DeviceType>(() => {
    const width = windowSize.value.width;
    if (width < 768) return "mobile";
    if (width < 1024) return "tablet";
    return "desktop";
  });

  const isMobile = computed(() => deviceType.value === "mobile");
  const isTablet = computed(() => deviceType.value === "tablet");
  const isDesktop = computed(() => deviceType.value === "desktop");

  const sidebarWidth = computed(() => {
    if (isMobile.value) return sidebarCollapsed.value ? 0 : 280;
    return sidebarCollapsed.value ? 64 : 240;
  });

  const isOnlineStatus = computed(
    () => systemStatus.value.online && connectionStatus.value === "connected",
  );
  const isOffline = computed(() => !isOnlineStatus.value);
  const isMaintenance = computed(() => systemStatus.value.maintenance);
  const hasError = computed(() => error.value !== null);
  const unreadNotifications = computed(() =>
    notifications.value.filter((n) => !n.read),
  );
  const unreadCount = computed(() => unreadNotifications.value.length);
  const hasUnreadNotifications = computed(() => unreadCount.value > 0);

  const appVersion = computed(() => appInfo.value.version);
  const appName = computed(() => appInfo.value.name);
  const isProduction = computed(
    () => appInfo.value.environment === "production",
  );
  const isDevelopment = computed(
    () => appInfo.value.environment === "development",
  );

  const canUseFeature = computed(
    () => (feature: keyof typeof systemStatus.value.features) => {
      return systemStatus.value.features[feature] && !isMaintenance.value;
    },
  );

  const currentLimits = computed(() => systemStatus.value.limits);
  const systemStats = computed(() => systemStatus.value.stats);

  const isWithinLimits = computed(
    () => (type: keyof typeof systemStatus.value.limits, current: number) => {
      return current < systemStatus.value.limits[type];
    },
  );

  const formattedUptime = computed(() => {
    const uptime = systemStatus.value.uptime;
    const days = Math.floor(uptime / (24 * 60 * 60));
    const hours = Math.floor((uptime % (24 * 60 * 60)) / (60 * 60));
    const minutes = Math.floor((uptime % (60 * 60)) / 60);

    if (days > 0) {
      return `${days}天 ${hours}小时 ${minutes}分钟`;
    } else if (hours > 0) {
      return `${hours}小时 ${minutes}分钟`;
    } else {
      return `${minutes}分钟`;
    }
  });

  const currentBreadcrumbs = computed(() => breadcrumbs.value);
  const fullPageTitle = computed(() => {
    if (breadcrumbs.value.length > 0) {
      const titles = breadcrumbs.value.map((b) => b.title);
      return `${titles.join(" / ")} - ${appInfo.value.name}`;
    }
    return `${pageTitle.value} - ${appInfo.value.name}`;
  });

  // 动作
  const setLoading = (value: boolean, text = "") => {
    loading.value = value;
    loadingText.value = text;
  };

  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value;
  };

  const setSidebarCollapsed = (collapsed: boolean) => {
    sidebarCollapsed.value = collapsed;
  };

  const updateWindowSize = (size: WindowSize) => {
    windowSize.value = size;

    // 移动端自动收起侧边栏
    if (size.width < 768 && !sidebarCollapsed.value) {
      sidebarCollapsed.value = true;
    }
  };

  const setOnlineStatus = (online: boolean) => {
    isOnline.value = online;
  };

  const setPageVisible = (visible: boolean) => {
    isPageVisible.value = visible;
  };

  const addVisitedView = (view: VisitedView) => {
    const existingIndex = visitedViews.value.findIndex(
      (v) => v.path === view.path,
    );
    if (existingIndex > -1) {
      // 更新现有记录
      visitedViews.value[existingIndex] = view;
    } else {
      // 添加新记录
      visitedViews.value.push(view);

      // 限制最大记录数
      if (visitedViews.value.length > 20) {
        visitedViews.value.shift();
      }
    }
  };

  const removeVisitedView = (path: string) => {
    const index = visitedViews.value.findIndex((v) => v.path === path);
    if (index > -1) {
      visitedViews.value.splice(index, 1);
    }
  };

  const clearVisitedViews = () => {
    visitedViews.value = [];
  };

  const addCachedView = (name: string) => {
    if (!cachedViews.value.includes(name)) {
      cachedViews.value.push(name);
    }
  };

  const removeCachedView = (name: string) => {
    const index = cachedViews.value.indexOf(name);
    if (index > -1) {
      cachedViews.value.splice(index, 1);
    }
  };

  const clearCachedViews = () => {
    cachedViews.value = [];
  };

  const loadAppInfo = async () => {
    const response = await appApi.getAppInfo();
    appInfo.value = response.data;
    return response;
  };

  const loadSystemStatus = async () => {
    const response = await appApi.getSystemStatus();
    systemStatus.value = response.data;
    return response;
  };

  const checkHealth = async () => {
    try {
      const response = await appApi.healthCheck();
      connectionStatus.value = "connected";
      return response.data;
    } catch (error) {
      connectionStatus.value = "disconnected";
      throw error;
    }
  };

  const loadNotifications = async () => {
    const response = await appApi.getNotifications();
    notifications.value = response.data;
    return response;
  };

  const markNotificationAsRead = async (notificationId: string) => {
    await appApi.markNotificationAsRead(notificationId);

    const notification = notifications.value.find(
      (n) => n.id === notificationId,
    );
    if (notification) {
      notification.read = true;
      notification.readAt = new Date().toISOString();
    }
  };

  const addNotification = (
    notification: Omit<Notification, "id" | "createdAt">,
  ) => {
    const newNotification: Notification = {
      ...notification,
      id: Date.now().toString(),
      createdAt: new Date().toISOString(),
      read: false,
    };
    notifications.value.unshift(newNotification);
    return newNotification;
  };

  const showNotification = (
    message: string,
    type: "info" | "success" | "warning" | "error" = "info",
    duration = 5000,
  ) => {
    const notification = addNotification({
      title:
        type === "error"
          ? "错误"
          : type === "warning"
            ? "警告"
            : type === "success"
              ? "成功"
              : "信息",
      message,
      type,
      duration,
      actions: [],
    });

    // 自动移除通知
    if (duration > 0) {
      setTimeout(() => {
        const index = notifications.value.findIndex(
          (n) => n.id === notification.id,
        );
        if (index !== -1) {
          notifications.value.splice(index, 1);
        }
      }, duration);
    }

    return notification;
  };

  const setError = (errorMessage: string | null) => {
    error.value = errorMessage;
  };

  const clearError = () => {
    error.value = null;
  };

  const setBreadcrumbs = (items: BreadcrumbItem[]) => {
    breadcrumbs.value = items;
  };

  const setPageTitle = (title: string) => {
    pageTitle.value = title;
    document.title = fullPageTitle.value;
  };

  const updateActivity = () => {
    lastActivity.value = new Date();
    if (isIdle.value) {
      isIdle.value = false;
    }
  };

  const setIdle = (idle: boolean) => {
    isIdle.value = idle;
  };

  const updateAppConfig = (config: Partial<typeof appInfo.value>) => {
    appInfo.value = { ...appInfo.value, ...config };
  };

  // 初始化应用
  const initApp = async () => {
    try {
      setLoading(true, "初始化应用...");

      // 从本地存储恢复状态
      const savedSidebarState = localStorage.getItem("sidebar-collapsed");
      if (savedSidebarState !== null) {
        sidebarCollapsed.value = JSON.parse(savedSidebarState);
      }

      // 并行加载基础信息
      await Promise.all([
        loadAppInfo().catch(() => {}), // 静默处理错误
        loadSystemStatus().catch(() => {}),
        loadNotifications().catch(() => {}),
      ]);

      // 从环境变量更新配置
      updateAppConfig({
        name: import.meta.env.VITE_APP_TITLE || "CardCaptorSakura",
        version: import.meta.env.VITE_APP_VERSION || "1.0.0",
        buildTime:
          import.meta.env.VITE_APP_BUILD_TIME || new Date().toISOString(),
        environment: import.meta.env.MODE || "development",
      });

      // 设置活动监听
      const activityEvents = [
        "mousedown",
        "mousemove",
        "keypress",
        "scroll",
        "touchstart",
      ];
      activityEvents.forEach((event) => {
        document.addEventListener(event, updateActivity, { passive: true });
      });

      // 设置空闲检测
      setInterval(() => {
        const now = new Date();
        const timeSinceLastActivity =
          now.getTime() - lastActivity.value.getTime();
        if (timeSinceLastActivity > idleTimeout.value && !isIdle.value) {
          setIdle(true);
        }
      }, 60000); // 每分钟检查一次

      // 设置在线状态监听
      window.addEventListener("online", () => {
        connectionStatus.value = "connected";
        showNotification("网络连接已恢复", "success");
      });

      window.addEventListener("offline", () => {
        connectionStatus.value = "disconnected";
        showNotification("网络连接已断开", "warning");
      });

      // 定期检查系统状态
      setInterval(async () => {
        try {
          await checkHealth();
        } catch (error) {
          // 静默处理健康检查失败
        }
      }, 30000); // 每30秒检查一次

      // 应用状态初始化完成
    } catch (error) {
      // 应用状态初始化失败
      setError("应用初始化失败");
      throw error;
    } finally {
      setLoading(false);
    }
  };

  // 保存状态到本地存储
  const saveState = () => {
    try {
      localStorage.setItem(
        "sidebar-collapsed",
        JSON.stringify(sidebarCollapsed.value),
      );
    } catch (error) {
      // 保存应用状态失败
    }
  };

  // 监听侧边栏状态变化并保存
  const unwatchSidebar = watch(sidebarCollapsed, saveState);

  // 清理函数
  const cleanup = () => {
    unwatchSidebar();
  };

  return {
    // 状态
    loading,
    loadingText,
    sidebarCollapsed,
    windowSize,
    isOnline,
    isPageVisible,
    visitedViews,
    cachedViews,
    appInfo,
    systemStatus,
    notifications,
    error,
    breadcrumbs,
    pageTitle,
    isFullscreen,
    connectionStatus,
    lastActivity,
    isIdle,
    idleTimeout,
    shortcuts,

    // 计算属性
    deviceType,
    isMobile,
    isTablet,
    isDesktop,
    sidebarWidth,
    isOnlineStatus,
    isOffline,
    isMaintenance,
    hasError,
    unreadNotifications,
    unreadCount,
    hasUnreadNotifications,
    appVersion,
    appName,
    isProduction,
    isDevelopment,
    canUseFeature,
    currentLimits,
    systemStats,
    isWithinLimits,
    formattedUptime,
    currentBreadcrumbs,
    fullPageTitle,

    // 方法
    setLoading,
    toggleSidebar,
    setSidebarCollapsed,
    updateWindowSize,
    setOnlineStatus,
    setPageVisible,
    addVisitedView,
    removeVisitedView,
    clearVisitedViews,
    addCachedView,
    removeCachedView,
    clearCachedViews,
    loadAppInfo,
    loadSystemStatus,
    checkHealth,
    loadNotifications,
    markNotificationAsRead,
    addNotification,
    showNotification,
    setError,
    clearError,
    setBreadcrumbs,
    setPageTitle,
    updateActivity,
    setIdle,
    updateAppConfig,
    initApp,
    saveState,
    cleanup,
  };
});
